package com.smartscreen.grademanage.service.impl;

import com.smartscreen.baseinfomanage.client.BaseInfoClient;
import com.smartscreen.grademanage.dto.StudentInfoDTO;
import com.smartscreen.grademanage.service.StudentInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class StudentInfoServiceImpl implements StudentInfoService {
    
    @Autowired
    private BaseInfoClient baseInfoClient;
    
    @Override
    @Cacheable(value = "students", key = "#studentIds.toString()")
    public Map<String, StudentInfoDTO> getStudentsBatch(List<String> studentIds) {
        try {
            Map<String, Map<String, Object>> rawData = baseInfoClient.getStudentsBatch(studentIds);
            return convertToStudentInfoDTOMap(rawData);
        } catch (Exception e) {
            log.error("批量获取学生信息失败", e);
            return Collections.emptyMap();
        }
    }
    
    @Override
    @Cacheable(value = "student", key = "#studentId")
    public StudentInfoDTO getStudentById(String studentId) {
        Map<String, StudentInfoDTO> studentMap = getStudentsBatch(Collections.singletonList(studentId));
        return studentMap.get(studentId);
    }
    
    /**
     * 将原始数据转换为StudentInfoDTO映射
     */
    private Map<String, StudentInfoDTO> convertToStudentInfoDTOMap(Map<String, Map<String, Object>> rawData) {
        if (rawData == null || rawData.isEmpty()) {
            return Collections.emptyMap();
        }
        
        return rawData.entrySet().stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        entry -> convertToStudentInfoDTO(entry.getValue()),
                        (existing, replacement) -> existing,
                        HashMap::new
                ));
    }
    
    /**
     * 将Map<String, Object>转换为StudentInfoDTO
     */
    private StudentInfoDTO convertToStudentInfoDTO(Map<String, Object> data) {
        if (data == null) {
            return null;
        }
        
        StudentInfoDTO dto = new StudentInfoDTO();
        
        try {
            dto.setStudentId(getStringValue(data, "studentId"));
            dto.setName(getStringValue(data, "name"));
            dto.setStudentNumber(getStringValue(data, "studentNumber"));
            dto.setClassId(getStringValue(data, "classId"));
            dto.setCreatedAt(getLocalDateTimeValue(data, "createdAt"));
            dto.setUpdatedAt(getLocalDateTimeValue(data, "updatedAt"));
        } catch (Exception e) {
            log.warn("转换学生信息时发生错误: {}", e.getMessage());
        }
        
        return dto;
    }
    
    /**
     * 安全获取字符串值
     */
    private String getStringValue(Map<String, Object> data, String key) {
        Object value = data.get(key);
        return value != null ? value.toString() : null;
    }
    
    /**
     * 安全获取LocalDateTime值
     */
    private LocalDateTime getLocalDateTimeValue(Map<String, Object> data, String key) {
        Object value = data.get(key);
        if (value == null) {
            return null;
        }
        
        try {
            if (value instanceof LocalDateTime) {
                return (LocalDateTime) value;
            } else if (value instanceof String) {
                // 尝试解析字符串格式的日期时间
                return LocalDateTime.parse((String) value, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
            }
        } catch (Exception e) {
            log.warn("解析日期时间失败: {}, 值: {}", e.getMessage(), value);
        }
        
        return null;
    }
}